﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.UI.WebControls;
using Mvc.XForms.UI.Settings;
using Mvc.XForms.Utilities;

namespace Mvc.XForms.UI {
	public class GridHeadSortable<T> : IGridHeadSortable {
		private readonly Expression<Func<T, object>> bind;
		private readonly IGridFormatter formatter;

		public string Label { get; set; }
		public CssClass CssClass { get; set; }
		public IDictionary<string, string> Attributes { get; set; }
		public bool IsCurrent { get; private set; }
		public string SortExpression { get; private set; }
		public SortDirection DefaultSortDirection { get; set; }
		public GridHeadSortableSettings Settings { get; set; }
		public IGrid Grid { get; set; }

		public GridHeadSortable(IGrid grid, IGridFormatter formatter, Expression<Func<T, object>> bind) {
			if (grid.Sorted == null)
				throw new InvalidOperationException("Grid model does not inherit from ISorted");

			this.bind = bind;
			this.formatter = formatter;

			CssClass = new CssClass();
			Grid = grid;
			SortExpression = bind.Body.ExtractID();
			IsCurrent = SortExpression == grid.Sorted.SortExpression;
			Settings = new GridHeadSortableSettings(this);
		}

		public string Render() {
			Label = Label ?? bind.Body.ExtractMember().CapitalizeSpace();

			var sortable = formatter.HeadSortable(this);
			return sortable;
		}
	}
}